import type Viewer from "../viewer";

export default class InputManager {
  // 视图
  public viewer: Viewer;
  // 鼠标是否被锁定
  public pointLock: Boolean = false;
  // 绑定事件
  public boundOnMouseDown: (evt: any) => void;
  public boundOnMouseMove: (evt: any) => void;
  public boundOnMouseUp: (evt: any) => void;
  public boundOnPointerlockChange: (evt: any) => void;
  public boundOnPointerlockError: (evt: any) => void;


  constructor(viewer: Viewer) {
    this.viewer = viewer;
    this.boundOnMouseDown = (e) => this.mouseDown(e);
    this.boundOnMouseMove = (e) => this.mouseMove(e);
    this.boundOnMouseUp = (e) => this.mouseUp(e);
    this.boundOnPointerlockChange = () => this.pointerLockChange();
    this.boundOnPointerlockError = (e: Error) => this.pointLockError(e);

    this.registerEvent();

  }

  mouseDown(evnet: MouseEvent) {
    this.viewer.domElement.requestPointerLock();
  }

  mouseMove(evnet: MouseEvent) {

  }

  mouseUp(evnet: MouseEvent) {

  }

  pointerLockChange() {
    if (document.pointerLockElement === this.viewer.domElement) {
      this.viewer.domElement.addEventListener('mousemove', this.boundOnMouseMove, false);
      this.viewer.domElement.addEventListener('mouseup', this.boundOnMouseUp, false);
      this.pointLock = true;
    } else {
      this.viewer.domElement.removeEventListener('mousemove', this.boundOnMouseMove, false);
      this.viewer.domElement.removeEventListener('mouseup', this.boundOnMouseUp, false);
      this.pointLock = false;
    }
  }

  pointLockError(e: Error) {
    console.error('[绑定失败]', e);
  }

  // 注册事件
  registerEvent() {
    // 注册MouseDown事件
    this.viewer.domElement.addEventListener('mousedown', this.boundOnMouseDown, false);
    document.addEventListener('pointerlockchange', this.boundOnPointerlockChange, false);
    document.addEventListener('pointerlockerror', this.boundOnPointerlockError, false);
  }

}